<script setup>
import { ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { projectListService, projectAddService, projectUpdateService, projectDeleteService } from '@/api/iimApi/project.js';
import { useProjectStore } from '@/stores/projectStore.js';

// 项目列表数据模型
const projects = ref([]);
const filteredProjects = ref([]);
const projectName = ref('');

// 分页条数据模型
const pageNum = ref(1); // 当前页
const total = ref(0); // 总条数
const pageSize = ref(3); // 每页条数

// 控制抽屉是否显示
const visibleDrawer = ref(false);
const isEdit = ref(false); // 控制是否为编辑状态

// 添加表单数据模型
const projectModel = ref({
  id: null,
  name: '',
  identifier: '',
  version: '',
  info: ''
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  identifier: [{ required: true, message: '项目标识不能为空', trigger: 'blur' }]
};

// 打开添加项目表单
const openAddProject = () => {
  isEdit.value = false;
  projectModel.value = {
    id: null,
    name: '',
    identifier: '',
    version: '',
    info: ''
  };
  visibleDrawer.value = true;
};

// 获取项目列表数据
const projectList = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    name: projectName.value ? projectName.value : null
  };
  let result = await projectListService(params);

  // 渲染视图
  projects.value = result.data.map(item => ({
    id: item.id,
    name: item.name,
    identifier: item.identifier,
    version: item.version,
    info: item.info
  }));
  filteredProjects.value = projects.value;
  total.value = filteredProjects.value.length;
};

// 计算当前页显示的数据
const paginatedProjects = computed(() => {
  const start = (pageNum.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredProjects.value.slice(start, end);
});

// 当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size;
  projectList();
};

// 当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num;
  projectList();
};

// 过滤项目列表
const filterProjects = () => {
  const query = projectName.value.toLowerCase();
  filteredProjects.value = projects.value.filter(project => 
    project.name.toLowerCase().includes(query) || 
    project.identifier.toLowerCase().includes(query)
  );
  total.value = filteredProjects.value.length;
};

// 重置搜索
const resetSearch = () => {
  projectName.value = '';
  filterProjects();
};

// Pinia store
const projectStore = useProjectStore();

// 选择项目
const selectProject = (project) => {
  projectStore.setSelectedProject(project);
  ElMessage.success(`已选择项目: ${project.name}`);
};

// 添加项目
const addProject = async () => {
  let result;
  if (isEdit.value) {
    result = await projectUpdateService(projectModel.value);
    ElMessage.success(result.msg ? result.msg : '修改成功');
    // 如果当前选中的项目是被修改的项目，则更新 Pinia 中存储的项目数据
    if (projectStore.selectedProject.id === projectModel.value.id) {
      projectStore.setSelectedProject(projectModel.value);
    }
  } else {
    result = await projectAddService(projectModel.value);
    ElMessage.success(result.msg ? result.msg : '添加成功');
  }
  visibleDrawer.value = false;
  projectList();
};

// 编辑项目
const editProject = (project) => {
  isEdit.value = true;
  projectModel.value = { ...project };
  visibleDrawer.value = true;
};

// 删除项目
const deleteProject = async (project) => {
  if (projectStore.selectedProject.id === project.id) {
    ElMessage.error('当前选中的项目不能删除');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `此操作将永久删除项目 "${project.name}" 及其所有相关数据, 是否继续?`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    await projectDeleteService(project.id);
    ElMessage.success('删除成功');
    projectList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 初始化项目列表
projectList();
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>项目信息管理</span>
        <div class="extra">
          <el-button type="primary" @click="openAddProject">添加项目</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="项目名称或标识：">
        <el-input placeholder="请输入项目名称或标识" v-model="projectName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="filterProjects">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 项目信息列表 -->
    <el-table :data="paginatedProjects" style="width: 100%">
      <el-table-column prop="name" label="项目名称" width="180" show-overflow-tooltip></el-table-column>
      <el-table-column prop="identifier" label="项目标识" width="180" show-overflow-tooltip></el-table-column>
      <el-table-column prop="version" label="项目版本" width="180" show-overflow-tooltip></el-table-column>
      <el-table-column prop="info" label="项目信息" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-space>
            <el-button @click="selectProject(scope.row)" type="success" size="small">选择</el-button>
            <el-button @click="editProject(scope.row)" type="primary" size="small">修改</el-button>
            <el-button @click="deleteProject(scope.row)" type="danger" size="small">删除</el-button>
          </el-space>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" :title="isEdit ? '修改项目' : '添加项目'" direction="rtl" size="50%">
      <!-- 添加项目表单 -->
      <el-form :model="projectModel" :rules="rules" label-width="100px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="projectModel.name" placeholder="请输入项目名称"></el-input>
        </el-form-item>
        <el-form-item label="项目标识" prop="identifier">
          <el-input v-model="projectModel.identifier" placeholder="请输入项目标识"></el-input>
        </el-form-item>
        <el-form-item label="项目版本">
          <el-input v-model="projectModel.version" placeholder="请输入项目版本"></el-input>
        </el-form-item>
        <el-form-item label="项目信息">
          <el-input type="textarea" v-model="projectModel.info" placeholder="请输入项目信息"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addProject">{{ isEdit ? '修改' : '添加' }}</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>